package v4

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/util"

	"math/rand"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strings"
	"time"

	wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

func Getbase64(c *gin.Context) {
	var imgUrl = c.DefaultQuery("url", "")
	//获取远端图片
	res, err := http.Get(imgUrl)
	if err != nil {
		c.String(http.StatusLengthRequired, "")
		return
	}

	defer res.Body.Close()
	var baseImg string
	// 读取获取的[]byte数据
	data, _ := ioutil.ReadAll(res.Body)

	imageBase64 := base64.StdEncoding.EncodeToString(data)

	mimeType := http.DetectContentType(data)

	switch mimeType {
	case "image/jpeg":
		baseImg = "data:image/jpeg;base64," + imageBase64
	case "image/png":
		baseImg = "data:image/png;base64," + imageBase64
	default:
		baseImg = imageBase64
	}
	c.String(http.StatusOK, baseImg)
	return
}

type GetPdfModel struct {
	Filename string  `json:"filename"`
	Xml      string  `json:"xml"`
	Height   float32 `json:"height"`
	Width    float32 `json:"width"`
}

func GetPdf(c *gin.Context) {
	var json GetPdfModel
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	filename := json.Filename
	svg := json.Xml
	dir := os.Getenv("WKHTMLTOPDF_PATH")
	fmt.Println(dir)

	pdfg, err := wkhtml.NewPDFGenerator()
	if err != nil {
		//log.Fatal(err)
		fmt.Println(err)
		if err := c.BindJSON(&json); err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": e.INVALID_PARAMS,
				"msg":  e.GetMsg(e.INVALID_PARAMS),
				"data": make(map[string]interface{}),
			})
			return
		}
	}

	// Set global options
	if json.Height > 1 {
		pdfg.Dpi.Set(96)
		h := json.Height / 3
		w := json.Width / 3.5
		pdfg.PageHeight.Set(uint(int32(h)) + 20)
		pdfg.PageWidth.Set(uint(int32(w)) + 20)
		pdfg.Grayscale.Set(false)
	} else {
		pdfg.Orientation.Set(wkhtml.OrientationPortrait)
		pdfg.Grayscale.Set(false)
	}

	enEscapeUrl, _ := url.QueryUnescape(svg)

	reg := regexp.MustCompile(`<text[^>]+.*?</text>`)
	enEscapeUrl = reg.ReplaceAllString(enEscapeUrl, "")
	html := "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><style>.geEditor {text-align: center;font-family:msyh,Arial,sans-serif;font-size:14px;border:none;margin:0px;}</style>"
	html = html + "<body class=\"geEditor\">"
	html = html + enEscapeUrl + "</body></html>"
	var page = wkhtml.NewPageReader(strings.NewReader(html))
	page.DisableSmartShrinking.Set(true)
	pdfg.AddPage(page)

	// Create PDF document in internal buffer
	err = pdfg.Create()
	if err != nil {
		util.WriteLog(filename + ":" + html)
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Transfer-Encoding", "binary")
	c.Data(http.StatusOK, "application/octet-stream", pdfg.Bytes())
}

func getRandstring(length int) string {
	if length < 1 {
		return ""
	}
	char := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	charArr := strings.Split(char, "")
	charlen := len(charArr)
	ran := rand.New(rand.NewSource(time.Now().Unix()))
	var rchar string = ""
	for i := 1; i <= length; i++ {
		rchar = rchar + charArr[ran.Intn(charlen)]
	}
	return rchar
}

// 随机文件名
func RandFileName() string {
	randStr := getRandstring(16)
	now := time.Now()
	has := md5.Sum([]byte(randStr + string(now.UnixNano())))
	return fmt.Sprintf("%x", has)
}
